<?php

/**
 * Description of createcomment
 *
 * @author libaoling
 * @time 2015-1-12
 */
class CreatecommentApp extends BackendApp
{

    private $_createcomment_mod;
    private $_goods_mod;

    public function __construct()
    {
        $this->CreatecommentApp();
    }

    public function CreatecommentApp()
    {
        parent::__construct();
        $this->_createcomment_mod = m("createcomment");
        $this->_goods_mod = m("goods");
    }

    public function index()
    {

        $cates = $this->_get_cate_options();
        $content = isset($_GET['content']) ? html_script(trim($_GET['content'])) : '';
        if ($content)
        {
            $conditions .= " AND content like '%{$content}%'";
        }

        $page = $this->_get_page();

        $list = $this->_createcomment_mod->find(array(
            'conditions' => "1 = 1" . $conditions,
            'count' => true,
            'limit' => $page['limit']
        ));

        $page['item_count'] = $this->_createcomment_mod->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign("cates", $cates);
        $this->assign("list", $list);
        $this->display("create_comment_index.html");
    }

    public function add()
    {
        if (!IS_POST)
        {
            $cates = $this->_get_cate_options();
            $this->assign("cates", $cates);

            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display("create_comment_form.html");
        }
        else
        {
            $data = array();
            $contents = explode("\n", $_POST['content']);
            foreach ($contents as $key => $content)
            {
                $data[$key]['user_name'] = $_SESSION['admin_info']['user_name'];
                $data[$key]['content'] = strip_tags($content);
                $data[$key]['cate_id'] = intval($_POST['cate_id']);
                $data[$key]['add_time'] = time();
            }

            if (!$this->_createcomment_mod->add($data))
            {
                $this->show_warning($this->_createcomment_mod->get_error());
                return;
            }

            $this->show_message('添加成功', 'back_list', 'index.php?app=createcomment', '继续添加', 'index.php?app=createcomment&amp;act=add'
            );
        }
    }

    public function edit()
    {
        $comment_id = isset($_GET['comment_id']) ? $_GET['comment_id'] : 0;
        if (!IS_POST)
        {
//            $cates = $this->_get_cate_options();
//            $this->assign("cates", $cates);
            $comment = $this->_createcomment_mod->get_info($comment_id);

            $this->assign("comment", $comment);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display("create_comment_form.html");
        }
        else
        {
            $data = $this->_get_post_data();
            $data['update_time'] = time();

            $this->_createcomment_mod->edit($comment_id, $data);

            $this->show_message('修改成功', 'back_list', 'index.php?app=createcomment'
            );
        }
    }

    public function drop()
    {
        $comment_ids = isset($_GET['id']) ? $_GET['id'] : 0;
        if (!$comment_ids)
        {
            $this->show_warning('请选择要删除的数据');

            return;
        }
        $ids = explode(',', $comment_ids); //获取一个类似array(1, 2, 3)的数组
        if (!$this->_createcomment_mod->drop($ids))    //删除
        {
            $this->show_warning($this->_createcomment_mod->get_error());

            return;
        }

        $this->show_message('删除成功');
    }

    //随机分配评论
    public function rand_assign_comment()
    {
        exit;
        $result = array();
        $cates = $this->_get_cate_options();
        $initArr = $this->_get_comment_rate();
        foreach ($cates as $cate_id => $cate)
        {
            $result[$cate_id] = $this->_get_goods_id_last($cate_id, $initArr);  //获取最后处理的商品id
        }
        $this->_insert_comment($result);
    }

    private function _insert_comment($result)
    {
        $goods_comment_mod = m("comment");
        foreach ($result as $cate_id => $v)
        {
            $data = array();
            $i = 0;
            $comments = $this->_get_comments($v['count']);  //随机获取n条评论
            $comments_count = count($comments);
            if (isset($v['info']) && $v['info'])
                foreach ($v['info'] as $count => $goods_ids)
                {
                    foreach ($goods_ids as $key => $goods_id)
                    {
                        for ($index = 0; $index < $count; $index++)
                        {
                            if ($comments)
                            {
                                $rand = rand(0, $comments_count - 1);
                                $data[$i]['goods_id'] = $goods_id;
                                $data[$i]['quantity'] = $this->_get_rand_num();
                                $data[$i]['from_user_name'] = $this->_get_rand_user_name();
                                $data[$i]['evaluation'] = $this->_get_rand_score();
                                $data[$i]['add_time'] = $this->_get_rand_time();
                                $data[$i]['comment'] = addslashes($comments[$rand]);
                                $i++;
                            }
                        }
                    }
                }
            $goods_comment_mod->add($data);
        }
    }

    private function _get_post_data()
    {
        return array(
            'user_name' => $_SESSION['admin_info']['user_name'],
            'content' => strip_tags($_POST['content']),
            'cate_id' => intval($_POST['cate_id']),
        );
    }

    private function _get_goods_id_last($cate_id, $initArr)
    {
        $return = array();
        $goods_ids = $this->_get_rand_goods_id($cate_id);
        $total_num = 0;

        foreach ($initArr as $key => $value)
        {
            foreach ($value['count'] as $count => $rate)
            {
                if (isset($goods_ids[$key]) && $goods_ids[$key])
                {
                    $num = ceil(count($goods_ids[$key]) * $rate);
                    $total_num += $num * $count;
                    if (!isset($return['info'][$count]))
                        $return['info'][$count] = array();
                    $return['info'][$count] = array_merge($return['info'][$count], array_splice($goods_ids[$key], 0, $num));
                }
            }
        }

        $return['count'] = $total_num;

        return $return;
    }

    private function _get_cate_options()
    {
        $cacheServer = cache_server();
        $key = "create_comment_get_cate_options";
        $result = $cacheServer->get($key);
        if ($result === false)
        {
            $list = $this->_goods_mod->find(array(
                'fields' => 'distinct cate_id, cate_name'
            ));

            foreach ($list as $v)
            {
                $cate_name = explode("\t", $v['cate_name']);
                $result[$v['cate_id']] = $cate_name[2];
            }
            $cacheServer->set($key, $result, 7200);
        }

        return $result;
    }

    private function _get_rand_score()
    {
        $arr = array(5, 5, 4, 5, 5);
        $i = rand(0, 4);
        return $arr[$i];
    }

    private function _get_rand_num()
    {
        $arr = array(1, 1, 1, 1, 1, 1, 2, 3);
        $i = rand(0, 7);
        return $arr[$i];
    }

    private function _get_rand_user_name()
    {
        $result = "";
        $str = "qwertyuiopasdfghjklzxcvbnm";
        $i = rand(7, 12);
        for ($index = 0; $index < $i; $index++)
        {
            $j = rand(0, strlen($str) - 1);
            $result .= $str{$j};
        }
        return $result;
    }

    private function _get_rand_time()
    {
        $date = rand(0, 76);  //30 + 31 + 15
        $begin = strtotime("2014-11-1 08:00:00");
        $end = strtotime("2014-11-2 01:00:00");
        $timestamp = rand($begin, $end) + $date * 24 * 3600;
        return $timestamp;
    }

    private function _get_rand_goods_id($cate_id)
    {
        $initArr = $this->_get_comment_rate();
        $result = array();
        $cate_sql = $cate_id ? " AND cate_id_3 = '{$cate_id}'" : '';

        $keys = array_keys($initArr);
        foreach ($keys as $key)
        {
            $sql = "SELECT goods_id FROM `wl_goods` where {$initArr[$key]['condition']} AND is_hot = 0 {$cate_sql}";
            $result[$key] = $this->_goods_mod->getCol($sql);
        }

        return $result;
    }

    private function _get_comment_rate()
    {
        return array(
            '0_199' => array(
                'rate' => 0.7,
                'condition' => 'price < 200',
                'count' => array(5 => 0.2, 8 => 0.3, 15 => 0.2)
            ),
            '200_499' => array(
                'rate' => 0.6,
                'condition' => 'price >= 200 AND price < 500',
                'count' => array(3 => 0.2, 5 => 0.25, 10 => 0.15)
            ),
            '500_1999' => array(
                'rate' => 0.5,
                'condition' => 'price >= 500 AND price < 2000',
                'count' => array(3 => 0.2, 5 => 0.2, 8 => 0.1)
            ),
            '2000' => array(
                'rate' => 0.4,
                'condition' => 'price >= 2000',
                'count' => array(2 => 0.2, 3 => 0.1, 4 => 0.1)
            )
        );
    }

    //随机获取多少条评论
    private function _get_comments($limit)
    {
        $sql = "SELECT content FROM `wl_create_comment` ORDER BY rand() LIMIT {$limit}";
        return $this->_goods_mod->getCol($sql);
    }

}
